package server

import (
	"context"
	"errors"
	"fmt"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_live"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"time"
)

func (s Server) ProvideTicket(ctx context.Context, req *pb.ProvideTicketReq) (*pb.ProvideTicketResp, error) {
	uids := make([]int64, 0)
	if req.IsAll {
		// 获取所有用户
		var err error
		uids, err = db_main.GetAllUserIds()
		if err != nil {
			return nil, fmt.Errorf("获取所有用户id失败: %v", err)
		}
	} else {
		for _, uid := range req.GetUids() {
			uids = append(uids, uid)
		}
	}

	if err := db_live.ProvideTicket(uids, int(req.GetQuantity()), int(req.ProvideType)); err != nil {
		return nil, err
	}
	return &pb.ProvideTicketResp{}, nil
}

func (s *Server) Ticket(ctx context.Context, r *pb.TicketReq) (*pb.TicketResp, error) {
	live, err := db_live.GetLiveParam(map[string]interface{}{"anchorid": r.AnchorId})
	if err != nil {
		return &pb.TicketResp{
			Status: 2,
		}, err
	}
	// 固定只消耗一张
	live.Ticket = 1

	if live.Liveid == 0 {
		return &pb.TicketResp{
			Status: 2,
		}, errors.New("直播不存在")
	}
	if live.Ticket == 0 {
		return &pb.TicketResp{
			Status: 1,
		}, nil
	}

	checked, err := db_live.TicketINLive(int(r.Uid), live.Liveid, cache.GetConfigPub().TicketSwitch)
	if err != nil {
		return &pb.TicketResp{
			Status: 1,
		}, nil
	}

	tl := &models_live.LiveTicketLog{
		UID:       int(r.Uid),
		AnchorID:  int(r.AnchorId),
		Liveid:    live.Liveid,
		Ticket:    live.Ticket,
		CreatedAt: time.Now().Unix(),
	}

	if !checked {
		err = db_live.TicketLog(tl)
		if err != nil {
			return &pb.TicketResp{
				Status: 2,
			}, err
		}
	}
	return &pb.TicketResp{
		Status: 1,
	}, nil
}

func (s *Server) TicketList(ctx context.Context, r *pb.TicketListReq) (*pb.TicketListResp, error) {
	ms, total, unUse, err := db_live.TicketList(int(r.GetUid()), int(r.Status), int(r.Page), int(r.Size))
	if err != nil {
		return nil, err
	}

	resp := &pb.TicketListResp{
		UnUse: unUse,
		Total: total,
	}

	now := time.Now()
	for _, m := range ms {
		info := &pb.TicketInfo{
			Id:         int64(m.ID),
			Status:     r.Status,
			UseTime:    time.Unix(m.CreatedAt, 64).Format("2006-01-02 15:04:05"),
			ExpireTime: time.Unix(m.CreatedAt+86400, 64).Format("2006-01-02 15:04:05"),
		}

		if r.Status == 0 {
			// 券超过24小时需要从新消耗
			if (now.Unix() - m.CreatedAt) > 86400 {
				info.Status = 2
			} else {
				info.Status = 1
			}
		}

		resp.List = append(resp.List, info)
	}

	return resp, nil
}
